<template>
	<u-popup bgColor="transparent" :show="showPoster" mode="center">
		<template>
			<view class="close">
				<w-icon name="close" size="24" @click="$emit('change',false)"></w-icon>
			</view>
			<view id="poster" class="poster_con" :style="poster_bg">
				<w-image :src="invitaion_code" width="73" height="73" class="invitaion_code"></w-image>
			</view>
		</template>
	</u-popup>
</template>

<script>
	import { base64ToPath } from 'image-tools';
	export default {
		props:{
			showPoster: {
				type: Boolean,
				default: false
			},
			poster_bg: {
				type: Object,
				default: {}
			},
			invitaion_code: {
				type:String,
				default:''
			}
		},
		model:{
			prop:'showPoster',
			event:'change'
		},
		data() {
			return {
				
			};
		},
		mounted() {
			
		},
		methods:{
			showError(){
				uni.showToast({
					icon:'error',
					title:"生成海报失败"
				})
				uni.hideLoading()
			},
			showLoading(){
				uni.showLoading({
					title:"生成中"
				})
			},
			//保存海报
			saveImage(url){
				let _this=this;
				base64ToPath(url).then(path=>{
					//#ifdef H5
						let a = document.createElement('a')
						a.setAttribute('download', "")
						a.setAttribute('href', path)
						document.body.appendChild(a);
						a.style.display = 'none'
						a.click()
						document.body.removeChild(a)
						uni.hideLoading()
						uni.$u.toast('图片已保存到系统相册')
					//#endif
					//#ifndef H5
						uni.saveImageToPhotosAlbum({
							filePath: path,
							success() {
								uni.hideLoading()
								uni.showToast({
									icon: "success",
									title: "保存成功"
								})
							},
							fail(err){
								uni.hideLoading()
								uni.$u.toast('失败');
							}
						})
					//#endif
				})
			},
		}
	}
</script>

<script module='poster' lang='renderjs'>
	import html2canvas from 'html2canvas'
	export default {
		data() {
			return {

			}
		},
		methods: {
			save(e, ownerVm) {
				ownerVm.callMethod('showLoading')
				const dom = document.getElementById('poster')
				html2canvas(dom, {
					width: dom.clientWidth,
					height: dom.clientHeight,
					scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
					scrollX: 0,
					scale: 5,
					dpi: 1000,
					imageTimeout:15000,
					useCORS: true,
				}).then((canvas)=>{
					ownerVm.callMethod('saveImage', canvas.toDataURL('image/png'))
				}).catch(e=>{
					ownerVm.callMethod('showError')
					console.log("生成失败",e);
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.poster_con{
		width: 625rpx;
		height: 1100rpx;
		background-size: 100% 100%;
		position: relative;
		
		.invitaion_code{
			position: absolute;
			right: 14rpx;
			bottom: 14rpx;
		}
	}
	.close{
		width: 100%;
		height: 80rpx;
		display: flex;
		justify-content: flex-end;
	}
	.btn{
		width: 100%;
		padding: 0 20rpx;
		margin-top: 40rpx;
		@extend .flex,.flex-js-sb;
		>.z-btn{
			height: 80rpx;
			width:252rpx;
			border-radius: 40rpx;
		}
	}
</style>
